<?php

namespace app\admin\business;

use think\Exception;

class AdminUser
{
    /**
     * 登录逻辑
     * @param $data
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function login($data)
    {
        $adminUser = self::getAdminUserByUsername($data['username']);  //self =$this 访问静态方法
        if (empty($adminUser)) {
            throw new Exception("用户不存在");
        }
        //验证密码
        if ($adminUser['password'] != md5($data['password'] . "_dandan")) {
            //在外面捕获 传递
            throw new Exception("密码错误");

        }

        //记录信息到数据库
        $updateDate = [
            "last_login_time" => time(),
            "last_login_ip" => request()->ip(),
            "update_time" => time(),
        ];
        $res = $adminUser->updateById($adminUser['id'], $updateDate);

        if (empty($res)) {
            throw new Exception("登录失败");
            //return show(config("status.error"), "登录失败1");
        }

        //存入session
        session(config("admin.session_admin"), $adminUser);
        return true;

    }

    /**
     * 通过用户名获取用户数据
     * @param $username
     * @return array|bool|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAdminUserByUsername($username)
    {

        $adminUserObj = new \app\common\model\mysql\AdminUser();
        $adminUser = $adminUserObj->getAdminUserByUsername($username);

        if (empty($adminUser) || $adminUser->status != config("status.mysql.table_normal")) {
            return false;
            //return show(config("status.error"), "该用户不存在");
        }
        $adminUser->toArray();
        return $adminUser;
    }

}